import yaml
from selenium import webdriver
from selenium.common.exceptions import *


class BasePage(object):
    # 初始化
    def __init__(self):
        # 创建浏览器
        self.driver = webdriver.Chrome("D:\软件安装目录\python\chromedriver.exe")
        self.driver.implicitly_wait(10)
        # 浏览器最大化
        self.driver.maximize_window()

    # 访问浏览器
    def open_url(self, url):
        self.driver.get(url)
        self.driver.implicitly_wait(10)

    # 定义各种定位元素的方式
    def localElement(self, locate_type, value):
        el = None
        if locate_type == 'id':
            el = self.driver.find_element_by_id(value)
        elif locate_type == 'name':
            el = self.driver.find_element_by_name(value)
        elif locate_type == 'class':
            el = self.driver.find_element_by_class_name(value)
        elif locate_type == 'xpath':
            el = self.driver.find_element_by_xpath(value)
        elif locate_type == 'tag':
            el = self.driver.find_element_by_tag_name(value)
        elif locate_type == 'css':
            el = self.driver.find_element_by_css_selector(value)
        elif locate_type == 'text':
            el = self.driver.find_element_by_link_text(value)
        elif locate_type == 'partial':
            el = self.driver.find_element_by_partial_link_text(value)
        elif locate_type == 'selector':
            el = self.driver.find_element_by_css_selector(value)
        if el is not None:
            return el

    # 定位元素，并进行点击操作
    def click(self, locate_type, value):
        el = self.localElement(locate_type, value)
        el.click()

    # 定位元素，并输入内容
    def input_data(self, locate_type, value, data):
        el = self.localElement(locate_type, value)
        el.send_keys(data)

    # 获取元素文本内容
    def get_text(self, locate_type, value):
        el = self.localElement(locate_type, value)
        return el.text

    # 获取元素属性
    def get_attribute(self, locate_type, value, data):
        el = self.localElement(locate_type, value)
        return el.get_attribute(data)

    # 关闭浏览器
    def close_driver(self):
        self.driver.quit()

    # 异常捕获-提示框
    def get_abnormal(self, locate_type, value, excepts, hint):
        try:
            el = self.get_text(locate_type, value)
        except excepts:
            print(hint)

    # 初始化Yaml

    # 获取select下拉框的值并进行点击
    def select(self, value, ints):
        ul = self.driver.find_elements_by_css_selector(value)
        # 返回的是list列表，下标从0开始
        # print(ul)
        ul[ints].click()

    def __del__(self):
        self.driver.close()

    def odd(self, value):
        try:
            result = self.get_text("xpath", value)
            return result
        except NoSuchElementException:
            return " Error: 未弹出错误框"
